// 景点子路由
const Router = require("@koa/router");
const router = new Router();//实例化路由对象
// 访问路径是 localhost:3000/travel/addTravel
const {TravelModel} = require("../database/index")//导入景点模型
const {where,Op} = require('sequelize')//ORM mysql操作的对象


// 路由中间件（配置路由）
router
    .post('/addTravel',async (ctx, next) =>{
        const {travelName,type,status,travelAddress,travelDesc} = ctx.request.body
        const travelImg = ctx.files[0].filename; // 获取上传的文件
        console.log("新增的景点:",travelName,travelAddress,status)
        try{
            const result = await TravelModel.create({
                travelName,
                type,
                status,
                travelAddress,
                travelDesc,
                travelImg
            })
            console.log(result.toJSON())
            ctx.body = {
                code:200,
                msg:"success"
            }
        }catch(error){
            console.log(error)
            ctx.body = {
                code:500,
                msg:"fail"
            }
        }
    })
    .delete('/deleteTravel', async (ctx, next) => {
        const trav_id = ctx.query.trav_id;
        console.log('删除的景点 ID:', trav_id);
        try {
            const result = await TravelModel.destroy({ where: { travId: trav_id } });
            console.log('删除结果:', result); 
            if (result > 0) {
                ctx.body = {
                    code: 200,
                    msg: '删除成功'
                };
            } else {
                ctx.body = {
                    code: 404,
                    msg: '景点不存在'
                };
            }
        } catch (error) {
            console.error('服务器错误:', error);
            ctx.body = {
                code: 500,
                msg: '服务器错误'
            };
        }
    })
    .get('/getAllTravelsByPage', async (ctx) => {
        const { type, travelInformation, currentPage = 1, pageSize = 10 } = ctx.request.query;
    
        // 过滤条件
        const where = {};
        if (type) {
             where.type = type; // 过滤用户类型
        }
        if (travelInformation) {
            where[Op.or] = [
                { travelName: { [Op.like]: `%${travelInformation}%` } }, // 模糊匹配景点名
                { travelAddress: { [Op.like]: `%${travelInformation}%` } }, // 模糊匹配景点地址
                { travelDesc: { [Op.like]: `%${travelInformation}%` } }, // 模糊匹配景点描述

            ];
        }
        // if (travelName) {
        //     where.travelName = { [Op.like]: `%${travelName}%` }; // 模糊匹配景点名
        // }
       
        // 获取总记录数
        const totalCount = await TravelModel.count({ where });
        // 获取分页数据
        const offset = (currentPage - 1) * pageSize;
        const travel = await TravelModel.findAll({
            where,
            limit: Number(pageSize),
            offset: offset,
        });
        // 返回结果
        ctx.body = {
        data: {
            rows: travel,
            count: totalCount,
        },
        };
    })

    .post('/updateTravel',async (ctx, next) =>{
        const {travelName,type,status,travelDesc,travelAddress,trav_id} = ctx.request.body
        const travelImg = ctx.files[0].filename; // 获取上传的文件
        console.log("修改的数据:",trav_id,travelName,travelDesc)
        try{
            const result = await TravelModel.update({
                travelName,
                type,
                status,
                travelAddress,
                travelDesc,
                travelImg
            },{
                where:{
                    travId:trav_id
                }
            })
            // console.log(result.toJSON())
            ctx.body = {
                code:200,
                msg:"success"
            }
        }catch(error){
            console.log(error)
            ctx.body = {
                code:500,
                msg:"fail"
            }
        }
    })

    


// 导出
module.exports = router